package com.hengxinguotong.zhihuichengjian.ui.lift.warning;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.google.gson.Gson;
import com.hengxinguotong.zhihuichengjian.R;
import com.hengxinguotong.zhihuichengjian.adapter.LiftWarningListAdapter;
import com.hengxinguotong.zhihuichengjian.ui.app.BaseFragment;
import com.hengxinguotong.zhihuichengjian.bean.LiftWarning;
import com.hengxinguotong.zhihuichengjian.bean.LiftWarningCount;
import com.hengxinguotong.zhihuichengjian.bean.LiftWarningCountRes;
import com.hengxinguotong.zhihuichengjian.ui.lift.OnActivityInteractionListener;
import com.hengxinguotong.zhihuichengjian.ui.lift.OnFragmentInteractionListener;
import com.hengxinguotong.zhihuichengjian.utils.Constants;
import com.hengxinguotong.zhihuichengjian.utils.SPUtil;
import com.hengxinguotong.zhihuichengjian.utils.Utils;
import com.hengxinguotong.zhihuichengjian.widget.view.PullableRecyclerView;
import com.jingchen.pulltorefresh.PullToRefreshLayout;
import com.lidroid.xutils.http.RequestParams;

import org.apache.http.entity.StringEntity;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link LiftWarningListFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class LiftWarningListFragment extends BaseFragment implements OnActivityInteractionListener {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String INDEX = "index";
    private static final String START_TIME = "startTime";
    private static final String END_TIME = "endTime";
    
    private Activity activity;

    @BindView(R.id.refresh_list)
    PullToRefreshLayout refreshList;
    @BindView(R.id.empty_img)
    ImageView emptyImg;

    private PullableRecyclerView dataRv;

    // TODO: Rename and change types of parameters
    private int index;
    private String startTime,//开始时间 格式：2019-02-23
            endTime;//结束时间

    private OnFragmentInteractionListener mListener;

    private List<LiftWarning> towerWarningList;
    private LiftWarningListAdapter liftWarningListAdapter;
    private int pageIndex = 1;
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case Constants.UPDATE:
                    LiftWarningCount liftWarningCount = (LiftWarningCount) msg.obj;
                    List<LiftWarning> datas = liftWarningCount.getData();
                    bindData(datas);
                    mListener.onFragmentInteraction(index, liftWarningCount.getCount());
                    break;
            }
        }
    };

    private void bindData(List<LiftWarning> datas) {
        if (pageIndex == 1)
        {
            refreshList.refreshFinish(PullToRefreshLayout.SUCCEED);
            towerWarningList = datas;
        } else
        {
            refreshList.loadmoreFinish(PullToRefreshLayout.SUCCEED);
            towerWarningList.addAll(datas);
        }
        showEmptyView(towerWarningList.size() == 0);
        if (datas.size() >= Utils.ONCECOUNT)
        {
            refreshList.setPullUpEnable(true);
        } else
        {
            refreshList.setPullUpEnable(false);
        }
        liftWarningListAdapter.setDataList(towerWarningList);
    }

    public LiftWarningListFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param index Parameter 1.
     * @return A new instance of fragment LiftWarningListFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static LiftWarningListFragment newInstance(int index, String startTime, String endTime) {
        LiftWarningListFragment fragment = new LiftWarningListFragment();
        Bundle args = new Bundle();
        args.putInt(INDEX, index);
        args.putString(START_TIME, startTime);
        args.putString(END_TIME, endTime);
        fragment.setArguments(args);
        return fragment;
    }

    public void setActivity(Activity activity) {
        this.activity = activity;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            index = getArguments().getInt(INDEX);
            startTime = getArguments().getString(START_TIME);
            endTime = getArguments().getString(END_TIME);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_lift_warning_list, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
        initData();
    }

    @Override
    public void onLazyLoad() {

    }

    private void initView() {
        refreshList.setPullUpEnable(false);
        refreshList.setOnPullListener(pullListener);
        dataRv = (PullableRecyclerView) refreshList.getPullableView();
        towerWarningList =  new ArrayList<>();
        liftWarningListAdapter = new LiftWarningListAdapter(activity, towerWarningList);
//        liftWarningListAdapter.setOnClickListener(this);
        dataRv.setAdapter(liftWarningListAdapter);
        dataRv.setItemAnimator(new DefaultItemAnimator());
        dataRv.setLayoutManager(new LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false));

    }

    private PullToRefreshLayout.OnPullListener pullListener = new PullToRefreshLayout.OnPullListener()
    {
        @Override
        public void onRefresh(PullToRefreshLayout pullToRefreshLayout)
        {
            pageIndex = 1;
            initData();
        }

        @Override
        public void onLoadMore(PullToRefreshLayout pullToRefreshLayout)
        {
            pageIndex = towerWarningList.size() / Utils.ONCECOUNT + 1;
            initData();
        }
    };

    private void initData(){
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                getLiftWarningList("搜索中…");
            }
        }, 500);
    }

    public void getLiftWarningList(String alert) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("constructionId", SPUtil.getString(activity,"constructionid"));
            jsonObject.put("pageNum", pageIndex + "");
//            jsonObject.put("equipmentId", 1 + "");//设备Id 获取某个塔吊设备的吊装循环数据、违章数据时必传，塔吊违章数据不需要传
            switch (index){
                case 0://预警1，报警2，全部传0
                    jsonObject.put("level", 1 + "");
                    break;
                case 1://预警1，报警2，全部传0
                    jsonObject.put("level", 2 + "");
                    break;
                case 2://预警1，报警2，全部传0
                    jsonObject.put("level", 0 + "");
                    break;
            }
            jsonObject.put("startTime", startTime);
            jsonObject.put("endTime", endTime);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestParams params = new RequestParams();
        params.addHeader("Content-type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Utils.requestData(alert, activity, "/lifterAlarm/listWarningData/" + SPUtil.getString(activity, "uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if (!Utils.isEmpty(json)) {
                    Gson gson = new Gson();
                    LiftWarningCountRes res = gson.fromJson(json, LiftWarningCountRes.class);
                    if(res.getStatus() == 1){
                        Message msg = handler.obtainMessage();
                        msg.what = Constants.UPDATE;
                        msg.obj = res.getValue();
                        msg.sendToTarget();
                    }else{
                        showToast(res.getMsg());
                        if (pageIndex == 1)
                        {
                            refreshList.refreshFinish(PullToRefreshLayout.FAIL);
                        } else
                        {
                            refreshList.loadmoreFinish(PullToRefreshLayout.FAIL);
                        }
                    }
                }else{
                    showToast("系统异常");
                    if (pageIndex == 1)
                    {
                        refreshList.refreshFinish(PullToRefreshLayout.FAIL);
                    } else
                    {
                        refreshList.loadmoreFinish(PullToRefreshLayout.FAIL);
                    }
                }
            }

            @Override
            public void onFailure(String json) {
                try {
                    JSONObject object = new JSONObject(json);
                    String msg = object.getString("msg");
                    showToast(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    showToast("系统异常");
                }
                if (pageIndex == 1)
                {
                    refreshList.refreshFinish(PullToRefreshLayout.FAIL);
                } else
                {
                    refreshList.loadmoreFinish(PullToRefreshLayout.FAIL);
                }
            }
        });
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void OnActivityInteraction(String startTime, String endTime) {
        this.startTime = startTime;
        this.endTime = endTime;
        initData();
    }

    private void showEmptyView(boolean isEmpty){
        if(isEmpty){
            emptyImg.setVisibility(View.VISIBLE);
        }else {
            emptyImg.setVisibility(View.GONE);
        }
    }

}
